package com.sca.common.netty.server;

import com.mask.common.core.exception.BaseException;
import com.sca.common.netty.config.NettyProperties;
import com.sca.common.netty.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * Netty服务器
 */
@Slf4j
@Component
public class NettyServer {
    
    @Autowired
    private NettyProperties nettyProperties;
    
    @Autowired
    private NettyServerHandler nettyServerHandler;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    
    @PostConstruct
    public void start() {
        if (!nettyProperties.isEnabled()) {
            return;
        }
        
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new IdleStateHandler(
                                            nettyProperties.getServer().getHeartbeatInterval(),
                                            0, 0, TimeUnit.SECONDS))
                                    .addLast(nettyServerHandler);
                        }
                    });
            
            ChannelFuture future = bootstrap.bind(
                    nettyProperties.getServer().getHost(),
                    nettyProperties.getServer().getPort()).sync();
            
            log.info("Netty服务器启动成功，监听端口：{}", nettyProperties.getServer().getPort());
            
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("Netty服务器启动失败", e);
            throw new BaseException("Netty服务器启动失败：" + e.getMessage());
        }
    }
    
    @PreDestroy
    public void destroy() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        log.info("Netty服务器已关闭");
    }
}